package com.genewu.cloud.jdbc;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.util.Properties;

import com.genewu.cloud.jdbc.core.DriverConstants;

public class UniversalDriver implements Driver {

	//
	// Register ourselves with the DriverManager
	//
	static {
		try {
			java.sql.DriverManager.registerDriver(new UniversalDriver());
		} catch (SQLException E) {
			throw new RuntimeException("Can't register driver!");
		}
	}
	
	
	Driver serviceDriver = null;

	static final String PACKAGE_NAME = "com.genewu.cloud.jdbc.impl.";

	static final String DRIVER_CLASS_NAME = ".ServiceDriverImpl";

	public boolean acceptsURL(String url) throws SQLException {
		boolean result = false;
		if (url.matches(DriverConstants.URL_PATTERN)) {
			findServiceDriver(url);
			result = serviceDriver.acceptsURL(url);
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	private void findServiceDriver(String url) throws SQLException {
		if (!url.matches(DriverConstants.URL_PATTERN)) {
			throw new SQLException("Illegal url : " + url
					+ " expect \"jdbc:universal:serviceid:url\"");
		}
		if (null == serviceDriver) {
			// jdbc:universal:serviceid:url
			String serviceId = url.split(":")[2];
			String driverName = PACKAGE_NAME + serviceId + DRIVER_CLASS_NAME;
			try {
				Class clazz = UniversalDriver.class.getClassLoader().loadClass(
						driverName);
				serviceDriver = (Driver) clazz.newInstance();
			} catch (ClassNotFoundException e) {
				throw new SQLException(
						"Could not Find service driver from url : " + url
								+ ", please make sure driver : " + driverName
								+ " in classpath.");
			} catch (InstantiationException e) {
				throw new SQLException(
						"Could not initialize service driver from url : " + url
								+ " driver : " + driverName);
			} catch (IllegalAccessException e) {
				throw new SQLException(
						"Illegal access service driver from url : " + url
								+ " driver : " + driverName);
			}
		}
	}

	public Connection connect(String url, Properties info) throws SQLException {
		findServiceDriver(url);
		checkDriver();
		return serviceDriver.connect(url, info);
	}

	private void checkDriver() throws SQLException {
		if (null == serviceDriver) {
			throw new SQLException("Unable to initialize unknown driver");
		}		
	}

	public int getMajorVersion() {
        if(null != serviceDriver)
    		return serviceDriver.getMajorVersion();
        else
            return 0;
	}

	public int getMinorVersion() {
        if(null != serviceDriver)
            return serviceDriver.getMinorVersion();
        else
            return 0;
	}

	public DriverPropertyInfo[] getPropertyInfo(String arg0, Properties arg1)
			throws SQLException {
		return serviceDriver.getPropertyInfo(arg0, arg1);
	}

	public boolean jdbcCompliant() {
		return true;
	}

}
